package cn.kgc.javaweb.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: mosin
 * @version: v1.0  2022/9/4
 * cookie的基本使用
 */
@WebServlet("/cookie")
public class CookieServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("缓存cookie的请求已被接收");
        // 如何手动创建cookie   缓存数据到客户端
        Cookie ck1 = new Cookie("username", "tom");
        Cookie ck2 = new Cookie("password", "123456");

        /**
         * 设置cookie的生存时间
         * 正数  单位秒
         * 负数  默认 关闭浏览器 清空cookie
         * 零   立即删除
         */
        ck1.setMaxAge(30);  //  秒
        ck2.setMaxAge(30);
        //绑定 缓存ck到响应对象
        resp.addCookie(ck1);
        resp.addCookie(ck2);
    }
}
